<template>
	<web-view :src="url" @message="bindmessage"></web-view>
</template>

<script>
	var _this;
	const app = getApp()
	export default {
		data() {
			return {
				url: '',
				path:'', //存放path地址 防止url处理之后path的参数与路径分离
				shareObj: '',
			}
		},
		onLoad(options) {
			_this = this;
			if (options.delUser == '1') {  //此处调用 是因为 下面url会带上token参数 不如不先清除 则会导致退出登录 页面还会显示用户信息
				uni.setStorageSync('logoutSelf', 1); //表示退出登录了
				uni.removeStorage({
					key: "userid",
					success: res => {
						app.globalData.userid = ''
					}
				})
				uni.removeStorage({
					key: "access_token",
				})
				uni.removeStorage({
					key: "refresh_token",
				})
				uni.removeStorage({
					key: "token_expired",
				})
				app.globalData.userid = null;
				app.globalData.access_token = null;
				app.globalData.refresh_token = null;
				app.globalData.token_expired = null;
			}
			let url = decodeURIComponent(options.url);
			_this.path = app.getUrlPara(url, 'path')
			let scene = parseInt(decodeURIComponent(options.scene));
			let join_backUrl = ''; //兼容注册返回的url
			if(url.indexOf('furl=') > -1){
				let param = url.split('furl=').length > 1 ? url.split('furl=')[1] : '';
				join_backUrl  = param && param.split('&')[0] || '';
			}
			url = url.replace('path=' + _this.path,'path=')
			url = url.replace('furl=' + join_backUrl,'furl=')
			url = url.replace('huoniaowh', '?').replace(/huoniaolj/g, '&').replace(/huoniaodh/g, '=');
			url = url.replace('path=','path=' + encodeURIComponent(_this.path))
			if(join_backUrl){
				url = url.replace('furl=','furl=' + encodeURIComponent(join_backUrl))
			}
			url = url.replace(/[?]/g, '&').replace('&', '?'); //如果是xxx.hmtl 直接被encode此时会直接变成xx.html&a=xx,会报错
			url = app.addUrlParam(url);
			console.log('链接地址：', decodeURIComponent(url));
			_this.getTitle(); //获取模块标题
			if (options.uid || options.userid) {
				uni.setStorage({
					key: "userid",
					data: options.uid || options.userid,
					success: res => {
						app.globalData.userid = options.uid || options.userid
					}
				})
				uni.setStorage({
					key: "access_token",
					data: options.access_token,
				})
				uni.setStorage({
					key: "refresh_token",
					data: options.refresh_token
				})
				var token_expired = Date.parse(new Date()) / 1000 + 7200 - 20; //两个小时有效期，保险起见，用1小时59分钟40秒
				uni.setStorage({
					key: "token_expired",
					data: token_expired
				})
				app.globalData.userid = options.uid;
				app.globalData.access_token = options.access_token;
				app.globalData.refresh_token = options.refresh_token;
				app.globalData.token_expired = token_expired;
			}
			
			if (options.redirectPath) { //登录处理
				options.redirectPath=options.redirectPath.replace('loginwh','?').replace(/loginlg/g,'&').replace(/logindh/g,'=');
				options.redirectPath = options.redirectPath.replace('huoniaowh', '?').replace(/huoniaolj/g, '&').replace(/huoniaodh/g, '=');
				var referpage = getCurrentPages()[0].__displayReporter.showReferpagepath; //上个页面
				//后退
				if (options.redirectPath == '/pages/goback') {
					//前面有页面时
					if (referpage) {
						uni.navigateBack({
							delta: 1
						})
					} else {
						uni.redirectTo({
							url: '/pages/index/index'
						})
					}
					return;
				}
				if (app.globalData.loginMode == 0) {
					uni.navigateBack({
						delta: 2,
						success: function(e) {
							//后退到上一页并重新打开登录前的页面
							uni.redirectTo({
								url: options.redirectPath,
							})
						},
						fail: function() {
							//没有上一页，在当前页直接打开
							uni.redirectTo({
								url: options.redirectPath
							})
						}
					})
				} else {
					uni.redirectTo({
						url: options.redirectPath
					})
				}
			}
			//自定义二维码
			if (scene) {
				console.log(scene)
				uni.showLoading({
					title: '加载中...',
				});
				_this.$ajax.get({
					url: 'include/ajax.php?service=siteConfig&action=getWxMiniProgramScene&scene=' + scene,
				}).then(res => {
					let data = res.data,
						state = data.state;
					if (state == "100") {
						let url = data.info;
						//直播
						if (url.indexOf('miniProgramLive_') > -1) {
							uni.redirectTo({
								url: 'plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=' +
									url.replace('miniProgramLive_', '')
							})
							
						
							// 跳转指定小程序
						}else if(url.includes('wxMiniprogram://')){
							let platForm = app.globalData.platForm
							var ahref = url.replace('wxMiniprogram://', '');
							var miniId = ahref.split('?/')[0];
							var //小程序原始id
								path = ahref.split('?/')[1]; //跳转的路径
							var _ghId = miniId.split('/')[0];
							var _appid = miniId.split('/')[1];
							var _path = path ? '/' + path : '';
							
							if(platForm == 'web' && window.appBoolean){
								window.setupWebViewJavascriptBridge(function (bridge) {
									if (path && path.indexOf('huoniao/') > -1) {
										bridge.callHandler('redirectToWxMiniProgram', { 'id': _ghId, 'path': path.replace('huoniao/', '/pages/redirect/index?url=/') }, function (responseData) { });
									} else {
										bridge.callHandler('redirectToWxMiniProgram', { 'id': _ghId, 'path': path }, function (responseData) { });
									}

								});
							}else if(platForm == 'mp-weixin'){
								uni.navigateToMiniProgram({
									appId: _appid,
									path: _path,
									success(res) {
										wx.navigateBack();
									},
									fail(res) {
										uni.showToast({
											title: res,
											icon: 'none',
											duration: 2000
										});
									}
								});
							}else{
								uni.showToast({
									title: '请在微信小程序中打开',
									icon: 'none',
									mask: true
								})
							}
							
							// 跳原生页面
						} else if(url.indexOf('http') < 0){
							 //判断是否指定城市，这里写此功能只需要一次就可以了，有必要的话，可以在落地页的onload里用option.cityid
							if(url.indexOf('cityid') > -1){
								console.log('发现cityid：' + url);
								var urlParam = url.split('?');
								var cityid = app.getUrlPara(urlParam[1], 'cityid');
								if(cityid && cityid != '0'){
									_this.$ajax.post({
										url: 'include/ajax.php?service=siteConfig&action=cityInfoById&cityid=' + cityid,
									}).then(res => {
										console.log('cityid信息：');
										console.log(res);
										var data = res.data, state = data.state;
										if (state == "100") {
											uni.setStorage({
												key:"cityInfo",
												data: JSON.stringify(data.info)
											})
											app.globalData.cityInfo = data.info;                        
										}
										
										uni.redirectTo({
											url: url
										})
									}).catch(res => {
										uni.redirectTo({
											url: url
										})
									})
								}else{
									uni.redirectTo({
										url: url
									})
								}
								//没有指定城市，直接打开指定页面
							}else{
								uni.redirectTo({
									url: url
								})
							}
							
						
						}else {
							_this.url = url
						}
						setTimeout(function() {
							uni.hideLoading();
						}, 2000);
					} else {
						uni.hideLoading();
						// uni.showToast({
						// 	title: data.info,
						// 	icon: 'none',
						// 	duration: 5000
						// });
						uni.showModal({
							title:'温馨提示',
							content: data.info,
							showCancel:false,
							success: function (res) {
								if (res.confirm) {
									//回首页
									// _this.url = app.globalData.masterDomain
									uni.redirectTo({
										url: '/pages/index/index'
									})
								} 
							}
						})
						//回首页
						// _this.url = app.globalData.masterDomain
					}
				}).catch(res => {
					uni.hideLoading();
					uni.showModal({
						title:'温馨提示',
						content: '解析失败，请确认二维码是否过期！',
						showCancel:false,
						success: function (res) {
							if (res.confirm) {
								//回首页
								// _this.url = app.globalData.masterDomain
								uni.redirectTo({
									url: '/pages/index/index'
								})
							} 
						}
					})
					// uni.showToast({
					// 	title: '解析失败，请确认二维码是否过期！',
					// 	icon: 'none',
					// 	duration: 5000
					// });
					//回首页
					// _this.url = app.globalData.masterDomain
				})
				//系统默认
			} else {
				if (url.indexOf('%3A%2F%2F') > -1 && url.indexOf('://') < 0) {
					url = decodeURIComponent(url);
				}
				//打开原生页面
				if (url.indexOf('path=/pages/') > -1 && url.indexOf('http') == -1) {
					var _path = app.getUrlPara(url, 'path');
					var referpage = getCurrentPages()[0].__displayReporter.showReferpagepath; //上个页面
					//后退
					if (_path == '/pages/goback') {
						//前面有页面时
						if (referpage) {
							uni.navigateBack({
								delta: 1
							})
						} else {
							uni.redirectTo({
								url: '/pages/index/index'
							})
						}
					} else {
						uni.redirectTo({
							url: _path,
						})
					}
					return false;
				}
				//后台自定义菜单支持小程序自定义链接
				if (url.indexOf('http') < 0) {
					url = app.globalData.masterDomain + url;
				}
				uni.showLoading({
					title: '加载中...',
				});
				_this.url = url;
				setTimeout(function() {
					uni.hideLoading();
				}, 2000);
			}
			// #ifndef H5
			// 显示转发选项
			uni.showShareMenu({
				withShareTicket: true,
			})
			// #endif
			// 分享关联绑定
			let fromShareVal= uni.getStorageSync('fromShare');
			if(fromShareVal){
				app.bindShareFn(fromShareVal);
			}
		},
		onShareAppMessage(res) {
			let shareObj = _this.shareObj;
			let title = shareObj.title;
			title = title ? title : app.globalData.appConfig.share.title;
			let pageUrl=decodeURIComponent(_this.url).replace(/access_token=([^&]*)&|&access_token=([^&]*)/,'').replace(/wxMiniProgramLoginByToken=([^&]*)&|&wxMiniProgramLoginByToken=([^&]*)/,'').replace(/fromShare=([^&]*)&|&fromShare=([^&]*)/,'').replace(/refresh_token=([^&]*)&|&refresh_token=([^&]*)/,'');
			pageUrl=`${pageUrl.replace('?','&')}&fromShare=${app.globalData.userid}`.replace('&','?');
			return {
				title: title,
				path:shareObj.link||pageUrl?'/pages/redirect/index?url=' + encodeURIComponent(shareObj?shareObj.link:pageUrl):'/pages/index/index',
				success: function(res) {
					// 转发成功
					console.log('成功');
				},
				fail: function(res) {
					// 转发失败
					console.log('失败');
				}
			}
		},
		onShareTimeline(res) {
			return {
				title: app.globalData.appConfig.share.title,
			};
		},
		methods: {
			bindmessage(e) {
				if (!e.detail) {
					return
				}
				let list = e.detail.data;
				if (!list || list.length === 0) {
					return
				}
				let info = list[list.length - 1];
				console.log('通讯数据：', info);
				_this.shareObj = info;
				if (info.title == '微信小程序登录') {
					console.log('小程序登录');
					uni.showLoading({
						title: '授权中...',
					});
					app.login(function() {
						uni.navigateTo({
							url: '/pages/redirect/index?url=' + encodeURIComponent(info.link)
						});
					});
					return;
				}
				if (!info.title) {
					console.error('分享信息错误', list)
					return
				}
				_this.title = info.title;
			},
			getTitle() {
				_this.$ajax.get({
					url: 'include/ajax.php?service=siteConfig&action=config'
				}).then(res => {
					let data = res.data,
						state = data.state;
					if (state == "100") {
						let list = data.info;
						uni.setNavigationBarTitle({
							title: list.shortName,
							success(res) {
								console.log("setNavigationBarTitle 调用成功");
							},
							fail(res) {
								console.log(`setNavigationBarTitle 调用失败:`, res.errMsg);
							},
						});
					}
				})
			},
		}
	}
</script>

<style>

</style>